﻿// ------------------------------------------------------------------------------------------------
//  <copyright file="Content.cs" company="Iveely">
//    Copyright (c) Iveely Liu.  All rights reserved.
//  </copyright>
//  
//  <Create Time>
//    12/03/2012 20:12 
//  </Create Time>
//  
//  <contact owner>
//    liufanping@iveely.com 
//  </contact owner>
//  -----------------------------------------------------------------------------------------------

#region

using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading;

#endregion

namespace IveelySE.Common.Log
{
    /// <summary>
    ///   企业应用框架的日志类
    /// </summary>
    /// <remarks>
    ///   此日志类提供高性能的日志记录实现。
    ///   当调用Write方法时不会造成线程阻塞,而是立即完成方法调用,因此调用线程不用等待日志写入文件之后才返回。
    /// </remarks>
    public class Content : IDisposable
    {
        /// <summary>
        ///   日志对象的缓存队列
        /// </summary>
        private static Queue<Message> _msgs;

        /// <summary>
        ///   日志文件保存的路径
        /// </summary>
        private static string _path;

        /// <summary>
        ///   日志写入线程的控制标记
        /// </summary>
        private static bool state;

        /// <summary>
        ///   日志记录的类型
        /// </summary>
        private static LogType type;

        /// <summary>
        ///   日志文件生命周期的时间标记
        /// </summary>
        private static DateTime TimeSign;

        /// <summary>
        ///   日志文件写入流对象
        /// </summary>
        private static StreamWriter writer;

        /// <summary>
        ///   唯一实例
        /// </summary>
        private static Content context=null;

        /// <summary>
        ///   创建日志对象的新实例，采用默认当前程序位置作为日志路径和默认的每日日志文件类型记录日志
        /// </summary>
        private Content()
            : this(".\\", LogType.Hourly)
        {
        }

        /// <summary>
        ///   创建日志对象的新实例，根据指定的日志文件路径和指定的日志文件创建类型
        /// </summary>
        /// <param name="p"> 日志文件保存路径 </param>
        /// <param name="t"> 日志文件创建方式的枚举 </param>
        public Content(string p, LogType t)
        {
            if(_msgs == null)
            {
                state = true;
                _path = p;
                type = t;
                _msgs = new Queue<Message>();
                var thread = new Thread(Work);
                thread.Start();
            }
        }

        /// <summary>
        ///   获取唯一实例
        /// </summary>
        /// <returns> </returns>
        public static Content GetInstance()
        {
            if(context == null)
            {
                return new Content();
            }

            return context;
        }

        /// <summary>
        ///   日志文件写入线程执行的方法
        /// </summary>
        private void Work()
        {
            while(true)
            {
                // 判断队列中是否存在待写入的日志
                if(_msgs.Count > 0)
                {
                    Message msg;
                    lock(_msgs)
                    {
                        msg = _msgs.Dequeue();
                    }
                    if(msg != null)
                    {
                        FileWrite(msg);
                    }
                }
                else
                {
                    // 判断是否已经发出终止日志并关闭的消息
                    if(state)
                    {
                        Thread.Sleep(1);
                    }
                    else
                    {
                        FileClose();
                    }
                }
            }
        }

        /// <summary>
        ///   根据日志类型获取日志文件名，并同时创建文件到期的时间标记
        ///   通过判断文件的到期时间标记将决定是否创建新文件
        /// </summary>
        /// <returns> </returns>
        private string GetFilename()
        {
            DateTime now = DateTime.Now;
            string format = string.Empty;
            switch(type)
            {
                case LogType.Hourly:
                    TimeSign = new DateTime(now.Year, now.Month, now.Day);
                    TimeSign = TimeSign.AddDays(1);
                    format = "yyyyMMddhh'.log'";
                    break;

                case LogType.Daily:
                    TimeSign = new DateTime(now.Year, now.Month, now.Day);
                    TimeSign = TimeSign.AddDays(1);
                    format = "yyyyMMdd'.log'";
                    break;
                case LogType.Weekly:
                    TimeSign = new DateTime(now.Year, now.Month, now.Day);
                    TimeSign = TimeSign.AddDays(7);
                    format = "yyyyMMdd'.log'";
                    break;
                case LogType.Monthly:
                    TimeSign = new DateTime(now.Year, now.Month, 1);
                    TimeSign = TimeSign.AddMonths(1);
                    format = "yyyyMM'.log'";
                    break;
                case LogType.Annually:
                    TimeSign = new DateTime(now.Year, 1, 1);
                    TimeSign = TimeSign.AddYears(1);
                    format = "yyyy'.log'";
                    break;
            }

            return now.ToString(format);
        }

        /// <summary>
        ///   写入日志文本到文件的方法
        /// </summary>
        /// <param name="msg"> </param>
        private void FileWrite(Message msg)
        {
            try
            {
                if(writer == null)
                {
                    FileOpen();
                }
                else
                {
                    // 判断文件到期标志，如果当前文件到期则关闭当前文件创建新的日志文件
                    if(DateTime.Now >= TimeSign)
                    {
                        FileClose();
                        FileOpen();
                    }
                    writer.Write(msg.Datetime);
                    writer.Write('\t');
                    writer.Write(msg.Type);
                    writer.Write('\t');
                    writer.WriteLine(msg.Text);
                    writer.Flush();
                }
            }
            catch(Exception e)
            {
                Console.Out.Write(e);
            }
        }

        /// <summary>
        ///   打开文件准备写入
        /// </summary>
        private void FileOpen()
        {
            writer = new StreamWriter(_path + GetFilename(), true, Encoding.UTF8);
        }

        /// <summary>
        ///   关闭打开的日志文件
        /// </summary>
        private void FileClose()
        {
            if(writer != null)
            {
                writer.Flush();
                writer.Close();
                writer.Dispose();
                writer = null;
            }
        }

        /// <summary>
        ///   写入新日志，根据指定的日志对象Msg
        /// </summary>
        /// <param name="msg"> 日志内容对象 </param>
        public void Write(Message msg)
        {
            if(msg != null)
            {
                lock(_msgs)
                {
                    _msgs.Enqueue(msg);
                }
            }
        }

        /// <summary>
        ///   写入新日志，根据指定的日志内容和信息类型，采用当前时间为日志时间写入新日志
        /// </summary>
        /// <param name="text"> 日志内容 </param>
        /// <param name="messageType">信息类型</param>
        public void Write(string text, MessageType messageType)
        {
            Write(new Message(text, messageType));
        }

        /// <summary>
        ///   写入新日志，根据指定的日志时间、日志内容和信息类型写入新日志
        /// </summary>
        /// <param name="dt"> 日志时间 </param>
        /// <param name="text"> 日志内容 </param>
        /// <param name="messageType"> 信息类型 </param>
        public void Write(DateTime dt, string text, MessageType messageType)
        {
            Write(new Message(dt, text, messageType));
        }

        /// <summary>
        ///   写入新日志，根据指定的异常类和信息类型写入新日志
        /// </summary>
        /// <param name="e"> 异常对象 </param>
        /// <param name="messageType"> 信息类型 </param>
        public void Write(Exception e, MessageType messageType)
        {
            Write(new Message(e.ToString(), messageType));
        }

        #region IDisposable 成员

        /// <summary>
        ///   销毁日志对象
        /// </summary>
        public void Dispose()
        {
            state = false;
        }

        #endregion
    }
}